﻿using ProxyPattern.BusinessQuerySystem;
using System;
using System.Configuration;
using System.Reflection;

namespace ProxyPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello ProxyPattern!");

            {
                // 代理模式demo
                Proxy proxy = new Proxy();
                proxy.Request();
            }

            {
                //代理模式实例应用
                //读取配置文件
                string proxy = ConfigurationManager.AppSettings["proxy"];

                //反射生成对象，针对抽象编程，客户端无须分辨真实主题类和代理类
                ISearcher searcher;
                searcher = (ISearcher)Assembly.Load("ProxyPattern").CreateInstance(proxy);
                // 只需搜索
                string result = searcher.DoSearch("杨过", "玉女心经");
                Console.WriteLine(result);
            }

            Console.ReadLine();
        }
    }


    #region 代理模式
    /// <summary>
    /// 抽象主题类
    /// </summary>
    abstract class Subject 
    {
        public abstract void Request();
    }

    /// <summary>
    /// 真实主题类
    /// </summary>
    class RealSubject : Subject
    {
        public override void Request()
        {
            Console.WriteLine("实现具体的业务方法。");
        }
    }

    /// <summary>
    /// 代理类
    /// </summary>
    class Proxy : Subject 
    {
        //维持一个对真实主题对象的引用
        private readonly RealSubject realSubject = new RealSubject();

        public void PreRequest()
        {
            Console.WriteLine("调用真实对象方法前的预处理业务。");
        }

        public override void Request()
        {
            PreRequest();
            realSubject.Request();
            PostRequest();
        }

        public void PostRequest()
        {
            Console.WriteLine("调用真实对象方法后的预处理业务。");
        }
    }

    #endregion
}
